<template>
  <div class="all">
    <el-row :gutter="20">
      <el-col :span="4">
        <el-card class="personNum" style="margin-left: 20px">
          <div slot="header" class="clearfix" style="text-align: center;">
            <div>当前在线人数 {{ onlineNum }} 人</div>
          </div>
          <div v-for="o in onlineList" :key="o" class="text item">
            <div style="cursor: pointer;" @click="getUsername(o)">{{ o }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="20">
        <el-card class="box-card"> <!-- 设置固定高度 -->
          <div slot="header" class="clearfix" style="text-align: center;">
            <span style="text-align: center;">聊天对象({{ chatting }})</span>
            <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button>
          </div>
          <div ref="messageContainer">
            <div v-for="message in myMessageList" :key="message.id" class="text item" :class="{ 'my_message': message.sender === user.username, 'to_message': message.sender !== user.username }">
              <div class="message-container">
                <!-- <div class="to_avator">
                <img :src="baseApi + '/avatar/' + user.avatarName" alt="Avatar">
              </div>
              <div class="message-content">
                <div class="to_time">{{ formattedDateTime(o.timestamp) }}</div>
                <div class="to_message">{{ o.content }}</div>
              </div> -->
                <div v-if="message.sender !== user.username" class="to_avator">
                  <!-- 如果是对方的消息，显示对方的头像 -->
                  <img :src="baseApi + '/avatar/' + getAvatarName(message.sender)" alt="Avatar">
                </div>
                <div class="message-content">
                  <div class="to_time">{{ formattedDateTime(message.timestamp) }}</div>
                  <div class="message-text">{{ message.content }}</div>
                </div>
                <div v-if="message.sender === user.username" class="my_avator">
                  <!-- 如果是自己的消息，显示自己的头像 -->
                  <img :src="baseApi + '/avatar/' + user.avatarName" alt="Avatar">
                </div>
              </div>
            </div>
          </div>
        </el-card>
        <div class="bottom-input">
          <input id="sendMessage" v-model="content" class="sendMessage" @keyup.enter="send">
          <el-button @click="send">发送</el-button>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import crudChatMessages from '@/api/chatMessages'
import { mapGetters } from 'vuex'
import { getTime } from '@/utils/dateFormat'
import crudUser from '@/api/system/user'

export default {
  data() {
    return {
      onlineNum: 0,
      content: null,
      chatting: '',
      myMessageList: [],
      nowTime: getTime(),
      welcomeMessage: '',
      onlineList: [],
      otherAvatarName: null
    }
  },
  computed: {
    ...mapGetters(['user', 'baseApi'])

  },
  watch: {
    // 监听 myMessageList 的变化
    myMessageList() {
      // 当添加新消息时调用 scrollToBottom
      console.log('watch')
      this.scrollToBottom()
    }
  },
  mounted() {
    this.initWebSocket()
    this.scrollToBottom()
  },
  methods: {
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messageContainer
        console.log('Container Height:', container.clientHeight)
        console.log('Content Height:', container.scrollHeight)
        console.log('Scroll Top:', container.scrollTop)
        container.scrollTop = container.scrollHeight
      })
    },
    getAvatarName(data) {
      crudUser.getAvatarName(data).then(res => {
        this.otherAvatarName = res
      })
      return this.otherAvatarName
    },
    formattedDateTime(time) {
      return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
    },
    getUsername(data) {
      this.chatting = data
      this.getMessages(this.user.username, data)
    },
    async getMessages(sender, receiver) {
      await crudChatMessages.getMessage(sender, receiver).then(res => {
        this.myMessageList = res
      })
    },
    initWebSocket() {
      const wsUri = process.env.VUE_APP_WS_API + '/webSocket/' + this.user.username
      this.websock = new WebSocket(wsUri)
      this.websock.onerror = this.webSocketOnError
      this.websock.onmessage = this.webSocketOnMessage
    },
    webSocketOnError(e) {
      this.$notify({
        title: 'WebSocket连接发生错误',
        type: 'error',
        duration: 0
      })
    },
    webSocketOnMessage(e) {
      var obj = JSON.parse(e.data)
      console.log(obj)
      // this.myMessageList.push(messageObject)
      if (obj.messageType === 1) {
        // 把名称放入到selection当中供选择
        var onlineName = obj.username
        this.$message({ message: onlineName + '上线了', type: 'success' })
      } else if (obj.messageType === 2) {
        var offlineName = obj.username
        this.$message({ message: offlineName + '下线了', type: 'error' })
        this.onlineList = obj.onlineUsers
        this.onlineNum = obj.onlineUsers.length
      } else if (obj.messageType === 3) {
        this.onlineList = obj.onlineUsers
        this.onlineNum = obj.onlineUsers.length
      } else {
        this.myMessageList.push(obj)
      }
    },
    send() {
      if (this.chatting === '') {
        this.$message({
          message: '请选择聊天对象',
          type: 'danger'
        })
      } else {
        var chatObject = {}
        chatObject.type = 'message'
        chatObject.content = this.content
        chatObject.sender = this.user.username
        chatObject.receiver = this.chatting
        chatObject.timestamp = new Date().getTime()

        this.websock.send(JSON.stringify(chatObject))
        this.$message({
          message: '发送成功',
          type: 'success'
        })
        this.content = null
      }
    }
  }
}
</script>

<style>
.all {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.box-card {
  height: 400px; /* 设置固定高度 */
  overflow: auto; /* 使用 overflow:auto 使得内容超出高度时出现滚动条 */
}

.box-card .clearfix {
  position: sticky;
  top: 0;
  z-index: 1;
  background-color: #f5f5f5;
}

.bottom-input {
  background-color: #f5f5f5;
  padding: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.sendMessage {
  width: 92%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

el-button {
  width: 25%;
  padding: 10px;
}

.to_avator img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  vertical-align: middle;
}

.to_message {
  font-size: 14px;
  margin-left: 10px;
  background-color: #fff;
  padding: 10px;
  border-radius: 10px;
  box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1);
}

.to_time {
  display: inline-block;
  position: relative;
  /* left: 10px; */
}

.my_avator img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.my_message {
  font-size: 14px;
  margin-left: 10px;
  background-color: #007bff;
  color: #fff;
  padding: 10px;
  border-radius: 10px;
  box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1);
}

.message-container {
  display: flex;
  align-items: center;
}

.to_avator {
  margin-right: 10px;
}

.message-content {
  flex: 1;
}

.to_message {
  font-size: 14px;
  background-color: #fff;
  padding: 10px;
  border-radius: 10px;
  box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1);
}

.to_time {
  font-size: 12px;
  color: #000;
}

.my_message {
  display: flex;
  justify-content: flex-end;
}

.my_message .message-container {
  display: flex;
  align-items: center;
}

.my_message .to_avator {
  margin-left: 10px;
}

.my_message .message-content {
  flex: 1;
  text-align: right;
}

.to_message {
  display: flex;
}

.to_message .message-container {
  display: flex;
  align-items: center;
}

.to_message .my_avator {
  margin-right: 10px;
}

.to_message .message-content {
  flex: 1;
}

.to_message .to_message {
  text-align: left;
}
</style>
